package com.ychs.filter;

import com.ychs.entity.User;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * copyright(c)2021 YYB.ALL rights Reserved
 * <p>
 * 描述:
 *
 * @author 原玉波
 * @version 1.0
 * @date 2021/7/13
 */
public class LoginFilter implements Filter {
    private Logger logger = Logger.getLogger(this.getClass());
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        logger.info("进入登录过滤器");
        //获取当前的请求路径
        HttpServletRequest request = (HttpServletRequest) req;
        String uri = request.getRequestURI();
        logger.info("uri:"+uri);

        //如果是静态资源，则放行
        if((uri.indexOf(".js")!=-1&&uri.indexOf(".jsp")==-1)
                ||uri.indexOf(".css")!=-1
                ||uri.indexOf(".jpg")!=-1
                ||uri.indexOf(".gif")!=-1
                ||uri.indexOf(".ico")!=-1
                ||uri.indexOf(".json")!=-1
                ||uri.indexOf(".woff")!=-1
                ||uri.indexOf(".ttf")!=-1
                ||uri.indexOf(".png")!=-1
                ||uri.indexOf(".json")!=-1){
            chain.doFilter(req, resp);
        }else{
            User user = (User) request.getSession().getAttribute("user");
            if(user!=null){
                chain.doFilter(req, resp);
            }else{
                //没有登录
                if(uri.indexOf("LoginServlet")!=-1||uri.indexOf("login.jsp")!=-1){
                    //正在登录
                    chain.doFilter(req, resp);
                }else{
                    HttpServletResponse response = (HttpServletResponse) resp;
                    //获取项目的名称
                    String context = request.getContextPath();
                    //没有登录则去登录页面
                    response.sendRedirect(context+"/login.jsp");
                }
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
